﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace FluentPS.Mapping
{
    public class RowDataAdapter
    {
        public static bool IsColumnDataNull(DataRow row, string columnName)
        {
            if (row == null || string.IsNullOrEmpty(columnName))
                throw new ArgumentNullException();
            var rowValue = row[columnName];
            return (rowValue == DBNull.Value);
        }

        public static object GetRowData(DataRow row, string columnName, Type dataType, DataRowVersion dataRowVersion)
        {
            object defaultValue = dataType.IsValueType ? Activator.CreateInstance(dataType) : null;
            return GetRowData<object>(row, columnName, dataRowVersion) ?? defaultValue;
        }

        public static object GetRowData(DataRow row, string columnName, Type dataType)
        {
            object defaultValue = dataType.IsValueType ? Activator.CreateInstance(dataType) : null;
            return GetRowData<object>(row, columnName) ?? defaultValue;
        }

        public static T GetRowData<T>(DataRow row, string columnName)
        {
            return GetRowData<T>(row, columnName, DataRowVersion.Default);
        }

        public static T GetRowData<T>(DataRow row, string columnName, DataRowVersion dataRowVersion)
        {
            if (row == null || string.IsNullOrEmpty(columnName))
                throw new ArgumentNullException();

            object rowValue = DBNull.Value;
            try
            {
                if (row.HasVersion(dataRowVersion))
                    rowValue = row[columnName, dataRowVersion];
            }
            catch
            {
            }
            return (rowValue == DBNull.Value) ? default(T) : (T)rowValue;
        }

        internal static void SetRowData(DataRow row, string columnName, object data)
        {
            row[columnName] = data;
        }
    }
}
